//
//  QFNetworkTool.swift
//  sinaWeibo
//
//  Created by apple on 16/2/28.
//  Copyright © 2016年 Qifeng Yan. All rights reserved.
//

import UIKit
import AFNetworking // 导入第三方 网路请求

/// 自定义错误
enum QFNetworkToolError: Int {
    case AccessTokenEmpty = -1
    case UidEmpty = -2
    
    // 枚举可以定义属性
    var errorMessage: String {
        get {
            switch self {
            case AccessTokenEmpty: return "access_token 没有值"
            case UidEmpty: return "uid 没有值"
            }
        }
    }
    
    // 枚举 还可以定义方法
    func error() -> NSError {
        return NSError(domain: "cn.itcast.net", code: self.rawValue, userInfo: ["errorMessage": self.errorMessage])
    }
}

class QFNetworkTool: NSObject {
    
    
    
    // 创建一个网路单例对象
    static let sharedInstance: QFNetworkTool = QFNetworkTool()
    
    
    let afnManager: AFHTTPSessionManager // 定义一个网络请求对象
    
    // MARK: - 重写 构造方法，定义为私有，这样外界就不能调用构造方法 只能通过单例猜创建对象，以保证对象的唯一性
    private override init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        afnManager = AFHTTPSessionManager(baseURL: baseURL)
        
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    
    // MARK: - oauth授权相关
    let client_id = "3165314916"
    let client_secret = "967afe2dd64a84f7be9e318e8e45ca2f"
    let redirect_uri = "http://www.baidu.com/"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    // https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
    /// 获取oauth 授权的登陆地址(按照格式拼接)
    func oauthLoginURL() -> NSURL {
        let urlString = oauthUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        return NSURL(string: urlString)!
    }
    
    /// 获取Accesstoken
    // accessTokenFinished: (result: [String: NSObject]?, error: NSError?) -> ()
    // 定义一个闭包 来接收 Accesstoken 请求成功的回调
    // MARK: - 定义闭包
    typealias finishedCallBack = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    func loadAccesstoken(code: String, accessTokenFinished: finishedCallBack) {
        // 1 请求地址 
        let requestUrl = "https://api.weibo.com/oauth2/access_token"
        
        // 2 请求参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 3 发送post请求
        afnManager.POST(requestUrl, parameters: parameters, progress: nil, success: { (_, response) -> Void in
            let dict = response as? [String: NSObject] // 需要将response 强制转换为 字典
            accessTokenFinished(result: dict, error:nil)
            }) { (_, error) -> Void in
                accessTokenFinished(result: nil, error: error)
        }
    }
    
    /* 加载用户信息 要将网络请求到的数据传输出去  所以要准备一个闭包 finished: (result: [String: AnyObject]?, error: NSError) -> ()
    */
    
    func loadUserInfo(finished: finishedCallBack) {
        // 守卫
//        guard let access_token = QFUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//            // 模拟错误信息
//            let error = QFNetworkToolError.AccessTokenEmpty.error()
//            finished(result: nil, error: error)
//            return
//        }
        
        guard let uid = QFUserAccountViewModel.sharedInstance.userAccount?.uid else {
            // 模拟错误信息
            let error = QFNetworkToolError.UidEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        // 请求URL
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameter = ["uid" : uid]
        
        // 发送请求
        requestGET(urlString, parameter: parameter, finished: finished)
//        afnManager .GET(urlString, parameters: parameter, progress: nil, success: { (_, result) -> Void in
//            
//            finished(result: result as? [String : AnyObject], error: nil)
//            
//            }) { (_, error) -> Void in
//                
//                finished(result: nil, error: error)
//        }
    }
    
    /// 加载微博数据 发送请求
    func loadStatus(finished:finishedCallBack) {
        
//        guard let access_token = QFUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//            let error = QFNetworkToolError.UidEmpty.error()
//            finished(result: nil, error: error)
//            return
//        }
        
        // 请求URL
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 请求参数
//        let parameter = ["access_token": access_token]
        
        // 发送请求
        requestGET(urlString, parameter: nil, finished: finished)
//        afnManager.GET(urlString, parameters: parameter, progress: nil, success: { (_, result) -> Void in
//            // 请求数据成功回调
//            finished(result: result as? [String: AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                // 数据请求失败回调 
//                finished(result: nil, error: error)
//        }
    }
    
    
    // MARK; - 网络GET请求封装
    private func requestGET(urlString: String, var parameter: [String: AnyObject]?, finished:finishedCallBack) {
        
        guard let access_token = QFUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            let error = QFNetworkToolError.UidEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        if parameter == nil {
            parameter = [String: AnyObject]()
        }
        
        // 给参数拼接access_token
        parameter!["access_token"] = access_token
        
        // 发送请求
        afnManager.GET(urlString, parameters: parameter, progress: nil, success: { (_, result) -> Void in
            // 请求数据成功回调
            finished(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                // 数据请求失败回调
                finished(result: nil, error: error)
        }
    }
    
}










